package com.zkjl.protect_business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.google.common.collect.Lists;
import com.zkjl.protect_business.common.BaseException;
import com.zkjl.protect_business.common.Status;
import com.zkjl.protect_business.dto.AssessmentPoliticalDTO;
import com.zkjl.protect_business.dto.PageBaseDTO;
import com.zkjl.protect_business.dto.SortDTO;
import com.zkjl.protect_business.dto.businessType.BusinessDTO;
import com.zkjl.protect_business.entity.AssessmentPolitical;
import com.zkjl.protect_business.entity.Business;
import com.zkjl.protect_business.entity.BusinessField;
import com.zkjl.protect_business.repository.AssessmentPoliticalRepository;
import com.zkjl.protect_business.service.AssessmentPoliticalService;
import com.zkjl.protect_business.service.BusinessService;
import com.zkjl.protect_business.service.LogService;
import com.zkjl.protect_business.utils.QueryUtil;
import com.zkjl.protect_business.vo.statistic.GroupVO;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.zkjl.protect_business.common.Consts.*;

@Service
public class AssessmentPoliticalServiceImpl implements AssessmentPoliticalService {

    @Autowired
    ModelMapper modelMapper;
    @Autowired
    AssessmentPoliticalRepository assessmentPoliticalRepository;
    @Autowired
    BusinessService businessService;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    LogService logService;


    @Override
    public AssessmentPolitical save(AssessmentPoliticalDTO assessmentPoliticalDTO, String businessId) {

        AssessmentPolitical assessmentPolitical = modelMapper.map(assessmentPoliticalDTO, AssessmentPolitical.class);
        assessmentPolitical.setId(IdUtil.simpleUUID());
        assessmentPolitical.setBaseInfo();
        String name = assessmentPolitical.getName();

        List<AssessmentPolitical> allByName = assessmentPoliticalRepository.findAllByName(name);
        if (CollUtil.isNotEmpty(allByName)) {
            throw new BaseException(Status.DATA_EXIST.getCode(), "考核名称已存在，请确认后重试！");
        }

        //当前政治考核内包含的字段
        List<BusinessField> fields = assessmentPoliticalDTO.getFields();
        if (CollUtil.isEmpty(fields)) {
            fields = new ArrayList<>();
        }

        //新增业务分类，作为政治考核的子业务，用作后续通用文档索引查询
        BusinessDTO businessDTO = new BusinessDTO();
        businessDTO.setPid(businessId);
        businessDTO.setFields(fields);
        businessDTO.setName(name);  //用来后面统一查询
        businessDTO.setInvisible(true);    //这一级隐藏
        businessDTO.setOrgIds(assessmentPoliticalDTO.getOrgIds());

        businessDTO.setRouting("business");

        Business save = businessService.save(businessDTO);

        assessmentPolitical.setBusinessId(save.getId());
        AssessmentPolitical save1 = assessmentPoliticalRepository.save(assessmentPolitical);

        logService.save("政治考核", name,OPERATION_ADD);

        return save1;
    }

    @Override
    public PageImpl<AssessmentPolitical> page(PageBaseDTO pageBaseDTO, SortDTO sortDTO, String org, Long assessmentTime) {


        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder qb = QueryBuilders.boolQuery();

        if (StringUtils.isNotEmpty(org)) {
            qb.filter(new QueryStringQueryBuilder(org).field("org_name").defaultOperator(Operator.AND));
        }

        if (assessmentTime != null) {
            qb.filter(new QueryStringQueryBuilder(assessmentTime + "").field("assessment_time").defaultOperator(Operator.AND));
        }


        Pageable pageable = QueryUtil.build(qb, queryBuilder, pageBaseDTO, sortDTO, AssessmentPolitical.class);

        queryBuilder.withQuery(qb);

        SearchHits<AssessmentPolitical> search1 = elasticsearchRestTemplate.search(queryBuilder.build(), AssessmentPolitical.class);
        List<AssessmentPolitical> collect = search1.stream().map(search -> {

            AssessmentPolitical content = search.getContent();
            String businessId = content.getBusinessId();
            Long docNum = businessService.getDocNum(businessId);
            content.setNum(docNum);

            return content;

        }).collect(Collectors.toList());
        //处理考核人数


        long total = search1.getTotalHits();

        PageImpl page = new PageImpl(collect, pageable, total);

        return page;
    }

    @Override
    public Boolean del(String id) {

        AssessmentPolitical assessmentPolitical = get(id);
        logService.save("政治考核", assessmentPolitical.getName(), OPERATION_DEL);

        //然后删除下属业务
        Business business = businessService.getByName(assessmentPolitical.getName());
        if (business != null) {
            businessService.del(business.getId());
        }

        assessmentPoliticalRepository.deleteById(id);
        return true;
    }

    @Override
    public AssessmentPolitical get(String id) {

        Optional<AssessmentPolitical> repository = assessmentPoliticalRepository.findById(id);
        if (!repository.isPresent()) {
            throw new BaseException(Status.DATA_NOT_EXIST.getCode(), "未找到政治考核信息！");
        }
        AssessmentPolitical assessmentPolitical = repository.get();


        return assessmentPolitical;
    }


}
